﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Universum.Infrastructure.Configuration;
using System.Security.Principal;
using System.Web.Security;
using Universum.Infrastructure.Utils.Security;
using System.Threading;
using Universum;

namespace Universum
{
	public class should_contain_a_tilde : IRouteConstraint
	{
		#region IRouteConstraint Members

		public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
		{
			if (values.ContainsKey("username") == false) return false;
			string username = values["username"].ToString(); ;
			return username[0].Equals('~');
		}

		#endregion
	}
	// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
	// visit http://go.microsoft.com/?LinkId=9394801
	/// <summary>
	/// This is the application EntryPoint
	/// </summary>
	public class MvcApplication : System.Web.HttpApplication
	{
		public static void RegisterRoutes(RouteCollection routes)
		{
			// registers routes
			RoutesConfiguration.InitializeRoutes(routes);

		}

		protected void Application_Start()
		{
			// configures the application modules
			Bootstrap.BootstrapStructureMap();

			RegisterRoutes(RouteTable.Routes);
			// sets our IoC/DI to be the controller factory
			ControllerBuilder.Current.SetControllerFactory(typeof(StructureMapControllerFactory));
		}

		private void Application_OnAuthenticateRequest(object sender, EventArgs e)
		{
			// Customizes the identity
			IPrincipal curentIdentity = HttpContext.Current.User;
			if (curentIdentity != null)
				if (curentIdentity.Identity.IsAuthenticated && curentIdentity.Identity.AuthenticationType == "Forms")
				{
					FormsIdentity ident = (FormsIdentity)curentIdentity.Identity;
					
					UniversumPrincipal universumPrincipal = new UniversumPrincipal(ident);

					HttpContext.Current.User = universumPrincipal;
					Thread.CurrentPrincipal = universumPrincipal;

				}
		}
		private void Application_Error(Object sender, EventArgs e)
		{
			System.Exception oops = Server.GetLastError();
		
			System.Diagnostics.Trace.WriteLine(oops.Message);
			System.Diagnostics.Trace.WriteLine(oops.Source);
			System.Diagnostics.Trace.WriteLine(oops.StackTrace);
		}
	}
}